import { create, globSource } from "kubo-rpc-client";
import fs from "fs";
import got from "got";
import updater from "./updater.json" assert { type: "json" };
import runEnv from "./run.env.json" assert { type: "json" };

(async () => {
    const outputPath = "./dist";

    let ipfs = create({ host: "172.28.237.148", port: "5001", protocol: "http" });
    let { id } = await ipfs.id();
    console.log(id.toString());

    let file;
    for await (file of ipfs.addAll(globSource(outputPath, "**/*", { recursive: true, hidden: true }), { pin: false, wrapWithDirectory: true })) {
    }
    console.log(file.cid.toString());

    let codeHash = file.cid.toString();

    var options = {
        method: "post",
        headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,POST,OPTIONS" },
        https: { rejectUnauthorized: false },
        responseType: "json",
        timeout: { request: 10000 },
        json: {},
    };

    try {
        options.json = { codeHash, codeSize: file.size };

        let url = updater[runEnv.current] + "/feedback/publishVersion";
        console.log(url);
        let res = await got(url, options);
        if (res.statusCode !== 200) return console.error(res.statusCode, res.statusMessage, res.body);
        if (res.body.statusCode === 0) return console.log("发版成功", res.body.result);
        console.log(res.body);
    } catch (error) {
        console.log(error.toString());
    }
})();
